package com.polaris.live.im.sfs.processor.impl.system

import com.polaris.live.im.sfs.COMMAND_BATCH_COMMAND_ACK
import com.polaris.live.im.sfs.COMMAND_ERROR
import com.polaris.live.im.sfs.COMMAND_SUCCESS
import com.polaris.live.im.sfs.bean.pusher.PusherAckMessage
import com.polaris.live.im.sfs.bean.pusher.PusherNoticeMessage
import com.polaris.live.im.sfs.core.SmartFoxConnector
import com.polaris.live.im.sfs.core.SmartFoxQueueManager
import com.polaris.live.im.sfs.core.bean.DataArgument
import com.polaris.live.im.sfs.processor.MessageProcessSignal
import com.polaris.live.im.sfs.processor.ProceedMessageProcessSignal

/**
 * 推送ack处理
 *
 * @author Created by lucas on 2023/11/3 11:38
 * @since 1.0.0
 */
class PusherAckMessageProcessor : AbstractExcludeMessageProcessor() {

    //优先级最低，所有的处理完成后才能回执
    override fun order(): Int = Int.MIN_VALUE

    override fun shouldProcess(type: Int, command: String): Boolean {
        return type == SmartFoxConnector.CLIENT_PUSHER && command !in NOT_COMMANDS
    }

    override suspend fun process(type: Int, command: String, argument: DataArgument): MessageProcessSignal {
        val data = argument.getData<PusherNoticeMessage>() ?: return ProceedMessageProcessSignal
        if (data.needAck != true) {
            return ProceedMessageProcessSignal
        }

        return exclude(type, argument.command, data.msgId + "ack") {
            super.process(type, command, argument)
        }
    }

    override suspend fun handle(type: Int, command: String, argument: DataArgument) {
        val data = argument.getData<PusherNoticeMessage>() ?: return

        //如果需要ack则调用
        if (data.needAck == true) {
            ackMessage(command, data.msgId)
        }
    }

    private suspend fun ackMessage(command: String, msgId: String) {
        SmartFoxQueueManager.sendPusherMessage(
            COMMAND_BATCH_COMMAND_ACK,
            PusherAckMessage(command, listOf(msgId))
        )
    }

    companion object {

        val NOT_COMMANDS = setOf(
            COMMAND_SUCCESS,
            COMMAND_ERROR
        )

    }
}